package com.appkubes.mall.restful.application.common.sms.controller;

import com.appkubes.common.Response;
import com.appkubes.mall.restful.application.common.basic.SmsService;
import com.appkubes.mall.restful.application.common.basic.entity.dto.SmsCodeDTO;
import com.appkubes.mall.restful.application.common.sms.entity.vo.CodeVO;
import com.appkubes.mall.restful.application.common.sms.entity.vo.TelVo;
import com.appkubes.mall.restful.application.common.sms.service.CodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.Random;

@RestController
@Api("短信模块")
@Slf4j
@RequestMapping("/api/Ccode")
public class SmsCodeController {

    private static final String SMS_SUCCESS_CODE = "OK";

    @Autowired
    CodeService codeService;

    @Autowired
    SmsService<SmsCodeDTO> dahanSmsServiceImpl;

    @ApiOperation("发送验证码")
    @PostMapping("/getcode")
    public Response getcode(@RequestBody @Valid TelVo telVo, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return Response.error("参数错误");
        }

        if (codeService.getSmsSurvivor(telVo) != null) {
            return Response.error("请勿频繁操作");
        }

        String code = "";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            code += random.nextInt(10);
        }
        try {
            SmsCodeDTO smsCodeDTO = dahanSmsServiceImpl.sendSMS(telVo.getTel(), code, SmsCodeDTO.class);
            if (!"OK".equalsIgnoreCase(smsCodeDTO.getMessage())) {
                return Response.error(smsCodeDTO);
            }
        } catch (Exception e) {
            throw e;
//            return Response.error("验证码获取失败，服务器错误："+e.getMessage());
        }

        CodeVO codeVO = new CodeVO();
        codeVO.setCode(code);
        codeVO.setTel(telVo.getTel());
        codeService.addCode(codeVO);
        System.out.println("新增成功");
        return Response.success();
    }


}
